﻿using System.Runtime.Serialization.Formatters.Binary;

namespace OOP.Singleton.DesignPattern.Helper
{
    public class SerialHelper
    {
        public static string Serialize(object model)
        {
            using (MemoryStream ms = new MemoryStream())
            {
                BinaryFormatter formatter = new BinaryFormatter();
                formatter.Serialize(ms, model);
                ms.Flush();
                return Convert.ToBase64String(ms.ToArray());
            }
        }

        public static object Deserialize(string base64)
        {
            byte[] buff = Convert.FromBase64String(base64);
            using (MemoryStream ms = new MemoryStream(buff))
            {
                BinaryFormatter formatter = new BinaryFormatter();
                return formatter.Deserialize(ms);
            }
        }

        public static T DeepCopy<T>(T obj)
        {
            using (MemoryStream ms = new MemoryStream())
            {
                BinaryFormatter formatter = new BinaryFormatter();
                formatter.Serialize(ms, obj);
                ms.Seek(0, SeekOrigin.Begin);
                return (T)formatter.Deserialize(ms);
            }
        }
    }
}
